﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
namespace NfsCommon.Export
{
    public sealed class WebUtil
    {
        #region 获取URL参数

        /// <summary>
        /// Looks for a typed value passed either by QueryString or by Form. If
        /// not found then the default value is returned. Values in the QueryString
        /// override values passed by form.
        /// </summary>
        /// <param name="name">
        ///		Name of the value to look for.
        ///	</param>
        /// <param name="defaultValue">
        ///		Default value to use if it is not found.
        /// </param>
        /// <param name="context">
        ///		The HttpContext to reference from.
        /// </param>
        /// <returns>The first value found or defaultValue.</returns>
        public string GetQueryOrForm(string name, object defaultValue)
        {
            string[] values;

            values = HttpContext.Current.Request.QueryString.GetValues(name);
            if (values != null)
                return values[0];

            values = HttpContext.Current.Request.Form.GetValues(name);
            if (values != null)
                return values[0];

            if (defaultValue == null)
                return null;

            return defaultValue.ToString();
        }

        /// <summary>
        /// Looks for a typed value passed either by QueryString or by Form. If
        /// not found then the default value is returned. Values in the QueryString
        /// override values passed by form.
        /// </summary>
        /// <param name="name">
        ///		Name of the value to look for.
        ///	</param>
        /// <param name="defaultValue">
        ///		Default value to use if it is not found.
        /// </param>
        /// <param name="context">
        ///		The HttpContext to reference from.
        /// </param>
        /// <returns>The first value found or defaultValue.</returns>
        public string GetQueryOrForm(string name, string defaultValue)
        {
            try
            {
                return GetQueryOrForm(name, (object)defaultValue);
            }
            catch { }
            return defaultValue;
        }

        /// <summary>
        /// Looks for a typed value passed either by QueryString or by Form. If
        /// not found then the default value is returned. Values in the QueryString
        /// override values passed by form.
        /// </summary>
        /// <param name="name">
        ///		Name of the value to look for.
        ///	</param>
        /// <param name="defaultValue">
        ///		Default value to use if it is not found.
        /// </param>
        /// <param name="context">
        ///		The HttpContext to reference from.
        /// </param>
        /// <returns>The first value found or defaultValue.</returns>
        public int GetQueryOrForm(string name, int defaultValue)
        {
            try
            {
                return int.Parse(GetQueryOrForm(name, (object)defaultValue));
            }
            catch { }
            return defaultValue;
        }

        /// <summary>
        /// Looks for a typed value passed either by QueryString or by Form. If
        /// not found then the default value is returned. Values in the QueryString
        /// override values passed by form.
        /// </summary>
        /// <param name="name">
        ///		Name of the value to look for.
        ///	</param>
        /// <param name="defaultValue">
        ///		Default value to use if it is not found.
        /// </param>
        /// <param name="context">
        ///		The HttpContext to reference from.
        /// </param>
        /// <returns>The first value found or defaultValue.</returns>
        public decimal GetQueryOrForm(string name, decimal defaultValue)
        {
            try
            {
                return decimal.Parse(GetQueryOrForm(name, (object)defaultValue));
            }
            catch { }
            return defaultValue;
        }

        #endregion 获取URL参数

        #region 提示信息框

        /// <summary>
        /// 对客户端Web页面弹出警告信息
        /// </summary>
        /// <param name="page">Web页面,在页面中用this或this.Page</param>
        /// <param name="errMessage">错误信息</param>
        public void Alert(Page page, string errMessage)
        {
            Alert(page, errMessage, false);
        }

        /// <summary>
        /// 对客户端的Web页面弹出警告框并跳转页面
        /// </summary>
        /// <param name="page">Web页面,在页面中用this或this.Page</param>
        /// <param name="errMessage">弹出的信息</param>
        /// <param name="url">跳转的Url</param>
        public void Alert(Page page, string errMessage, string url)
        {
            errMessage = errMessage.Replace("\t\n", "");
            errMessage = errMessage.Replace("\r", "");
            errMessage = errMessage.Replace("\n", "\\n");

            string strAlertAndReturn = "alert('{0}');window.name = '__self';window.open('{1}', '__self');";

            string errContext = string.Format(strAlertAndReturn, errMessage, url);

            ClientScriptManager cs = page.ClientScript;
            cs.RegisterStartupScript(page.GetType(), "alert", errContext, true);

        }

        /// <summary>
        /// 对客户端的Web页面弹出警告框并关闭页面
        /// </summary>
        /// <param name="page"></param>
        /// <param name="closeWindow">是否关闭窗口</param>
        public void Alert(Page page, string errMessage, bool closeWindow, string returnValue = null)
        {
            errMessage = errMessage.Replace("\t\n", "");
            errMessage = errMessage.Replace("\r", "");
            errMessage = errMessage.Replace("\n", "\\n");
            errMessage = errMessage.Replace("'", "\\'");

            string strAlert = "alert('{0}');";
            string errContext = string.Format(strAlert, errMessage);
            if (closeWindow == true)
            {
                errContext += string.Format("window.returnValue={0};if (window.opener) window.opener.returnValue = {0}; window.close();", returnValue ?? "true");
            }

            ClientScriptManager cs = page.ClientScript;
            string strKey = DateTime.Now.ToString();
            int i = 0;
            for (i = 0; i < 100; i++)
            {
                if (!cs.IsClientScriptBlockRegistered(page.GetType(), strKey + i.ToString()))
                {
                    cs.RegisterStartupScript(page.GetType(), strKey + i.ToString(), errContext, true);
                    break;
                }
            }

            // cs.RegisterStartupScript(page.GetType(), "alert", errContext, true);
        }
        /// <summary>
        /// 对客户端的Web页面弹出警告框并关闭页面
        /// </summary>
        /// <param name="page"></param>
        /// <param name="closeWindow">是否关闭窗口</param>
        public void AlertCloseAndRefresh(Page page, string errMessage, string pagePath)
        {
            errMessage = errMessage.Replace("\t\n", "");
            errMessage = errMessage.Replace("\r", "");
            errMessage = errMessage.Replace("\n", "\\n");
            errMessage = errMessage.Replace("'", "\\'");

            string strAlert = "alert('{0}');";
            string errContext = string.Format(strAlert, errMessage);
            //alert(window.parent.window.OS);
            errContext += "window.parent.window.OS.Libraries.lightBox.closeLight({'action':'" + pagePath + "','refresh':'false','callback':function(){var obj=window.parent.window.$('input[autoclick]').eq(0)[0];if(obj)obj.click()}});";
            //if (closeWindow == true)
            //{
            //    errContext += string.Format("window.returnValue={0};if (window.opener) window.opener.returnValue = {0}; window.close();", returnValue ?? "true");
            //}

            ClientScriptManager cs = page.ClientScript;
            string strKey = DateTime.Now.ToString();
            int i = 0;
            for (i = 0; i < 100; i++)
            {
                if (!cs.IsClientScriptBlockRegistered(page.GetType(), strKey + i.ToString()))
                {
                    cs.RegisterStartupScript(page.GetType(), strKey + i.ToString(), errContext, true);
                    break;
                }
            }

            // cs.RegisterStartupScript(page.GetType(), "alert", errContext, true);
        }
        /// <summary>
        /// 对客户端的Web页面弹出警告框并关闭页面
        /// </summary>
        /// <param name="page"></param>
        /// <param name="closeWindow">关闭页面后是否刷新</param>
        public void AlertCloseAndRefresh(Page page, string errMessage, string pagePath, string Isrefresh)
        {
            errMessage = errMessage.Replace("\t\n", "");
            errMessage = errMessage.Replace("\r", "");
            errMessage = errMessage.Replace("\n", "\\n");
            errMessage = errMessage.Replace("'", "\\'");

            string strAlert = "alert('{0}');";
            string errContext = string.Format(strAlert, errMessage);
            //alert(window.parent.window.OS);
            errContext += "window.parent.window.OS.Libraries.lightBox.closeLight({'action':'" + pagePath + "','refresh':'" + Isrefresh + "','callback':function(){var obj=window.parent.window.$('input[autoclick]').eq(0)[0];if(obj)obj.click()}});";
            //if (closeWindow == true)
            //{
            //    errContext += string.Format("window.returnValue={0};if (window.opener) window.opener.returnValue = {0}; window.close();", returnValue ?? "true");
            //}

            ClientScriptManager cs = page.ClientScript;
            string strKey = DateTime.Now.ToString();
            int i = 0;
            for (i = 0; i < 100; i++)
            {
                if (!cs.IsClientScriptBlockRegistered(page.GetType(), strKey + i.ToString()))
                {
                    cs.RegisterStartupScript(page.GetType(), strKey + i.ToString(), errContext, true);
                    break;
                }
            }

            // cs.RegisterStartupScript(page.GetType(), "alert", errContext, true);
        }
        /// <summary>
        /// 对客户端的Web页面弹出警告框并关闭页面
        /// </summary>
        /// <param name="page"></param>
        /// <param name="closeWindow">是否关闭窗口</param>
        public void CloseAndRefresh(Page page, string pagePath)
        {


            string errContext = "";
            //alert(window.parent.window.OS);
            errContext += "window.parent.window.OS.Libraries.lightBox.closeLight({'action':'" + pagePath + "','refresh':'false','callback':function(){var obj=window.parent.window.$('input[autoclick]').eq(0)[0];if(obj)obj.click()}});";
            //if (closeWindow == true)
            //{
            //    errContext += string.Format("window.returnValue={0};if (window.opener) window.opener.returnValue = {0}; window.close();", returnValue ?? "true");
            //}

            ClientScriptManager cs = page.ClientScript;
            string strKey = DateTime.Now.ToString();
            int i = 0;
            for (i = 0; i < 100; i++)
            {
                if (!cs.IsClientScriptBlockRegistered(page.GetType(), strKey + i.ToString()))
                {
                    cs.RegisterStartupScript(page.GetType(), strKey + i.ToString(), errContext, true);
                    break;
                }
            }

            // cs.RegisterStartupScript(page.GetType(), "alert", errContext, true);
        }

        /// <summary>
        /// 弹出提示窗口
        /// </summary>
        /// <param name="page"></param>
        /// <param name="type">类型'successInfo','errorInfo''confirmInfo'</param>
        /// <param name="Message">提示信息</param>
        public void AlertInfo(Page page, string type, string Message, bool closeWindow)
        {
            //errMessage = errMessage.Replace("\t\n", "");
            //errMessage = errMessage.Replace("\r", "");
            //errMessage = errMessage.Replace("\n", "\\n");

            string strAlert = "AlertInfo('" + type + "','" + Message + "');";
            if (closeWindow == true)
            {
                strAlert += "window.returnValue=true;\n window.close();";
            }
            ClientScriptManager cs = page.ClientScript;
            string strKey = DateTime.Now.ToString();
            int i = 0;
            for (i = 0; i < 100; i++)
            {
                if (!cs.IsClientScriptBlockRegistered(page.GetType(), strKey + i.ToString()))
                {
                    cs.RegisterStartupScript(page.GetType(), strKey + i.ToString(), strAlert, true);
                    break;
                }
            }
            //ClientScriptManager cs = page.ClientScript;
            //cs.RegisterStartupScript(page.GetType(), "AlertInfo", strAlert, true);
        }

        #endregion 提示信息框

        #region 关闭窗口并返回值

        /// <summary>
        /// 关闭窗口并返回值
        /// </summary>
        /// <param name="page"></param>
        /// <param name="returnValue">页面返回值</param>
        public void CloseWindow(Page page, string returnValue)
        {
            string str = "window.returnValue={0};if (window.opener) window.opener.returnValue = {0}; window.close();";
            string strContext = string.Format(str, returnValue.Replace("'", "\\\'"));
            ClientScriptManager cs = page.ClientScript;
            cs.RegisterStartupScript(page.GetType(), "returnValue", strContext, true);
        }

        #endregion

        #region 上传文件

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="fileBytes">文件内容</param>
        /// <param name="uploadPath">文件路径，从ShopConfg获取</param>
        public void UpLoadFile(string fileName, byte[] fileBytes, string uploadPath)
        {

            if (string.IsNullOrEmpty(fileName))
                return;
            if (fileBytes.Length == 0)
                return;

            string fname = System.Web.HttpContext.Current.Server.MapPath(uploadPath) + fileName;
            FileInfo finfo = new FileInfo(fname);

            //删除原有文件
            if (finfo.Exists)
                finfo.Delete();

            //保存文件
            using (FileStream fs = finfo.OpenWrite())
            {
                fs.Write(fileBytes, 0, fileBytes.Length);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="uploadPath">文件路径，从ShopConfg获取</param>
        public void DeleteFile(string fileName, string uploadPath)
        {
            if (string.IsNullOrEmpty(fileName))
                return;

            string fname = System.Web.HttpContext.Current.Server.MapPath(uploadPath) + fileName;
            FileInfo finfo = new FileInfo(fname);

            //删除原有文件
            if (finfo.Exists)
                finfo.Delete();
        }

        #endregion

        #region 截取字符串

        public static string GetSubString(object obj, int length, bool showOrNot)
        {
            return GetSubString(obj, length, true, showOrNot);
        }

        public static string GetSubString(object obj, int length, bool showEllipsis, bool showOrNot)
        {
            if (obj != null && !string.IsNullOrEmpty(obj.ToString()))
            {
                return GetSubString(obj.ToString(), length, showEllipsis, showOrNot);
            }

            return string.Empty;
        }

        public static string GetSubString(string str, int length, bool showOrNot)
        {
            return GetSubString(str, length, true, showOrNot);
        }

        public static string GetSubString(string str, int length, bool showEllipsis, bool showOrNot)
        {
            string temp = NoHTML(str);

            if (temp.Length > length)
            {
                if (showEllipsis)
                {
                    if (showOrNot == true)
                    {
                        return temp.Substring(0, length);
                    }
                    else
                    {
                        return temp.Substring(0, length) + "…";
                    }

                }
                else
                {
                    return temp.Substring(0, length);
                }
            }
            else
                return temp;
        }

        public static string NoHTML(string Htmlstring)
        {

            //删除脚本  
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>[\s\S]*?<\/script>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<style[^>]*?>[\s\S]*?<\/style>", "", RegexOptions.IgnoreCase);

            //删除HTML  

            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"([rn])[s]+", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "xa1", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "xa2", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "xa3", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "xa9", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&#(d+);", "", RegexOptions.IgnoreCase);

            Htmlstring = Htmlstring.Replace("<", "");

            Htmlstring = Htmlstring.Replace(">", "");

            Htmlstring = Htmlstring.Replace("rn", "");

            Htmlstring = Htmlstring.Replace("&ldquo;", "");

            Htmlstring = Htmlstring.Replace("&rdquo;", "");

            Htmlstring = Htmlstring.Replace("”", "");

            Htmlstring = Htmlstring.Replace("“", "");

            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            Htmlstring = ClearString(Htmlstring);

            return Htmlstring;
        }

        private static string ClearString(string Htmlstring)
        {
            int iIndex = Htmlstring.IndexOf("{page:Section1;}");
            if (iIndex == -1)
            {
                return Htmlstring;
            }
            else
            {
                iIndex = iIndex + ("{page:Section1;}").Length;
                Htmlstring = Htmlstring.Substring(iIndex, Htmlstring.Length - iIndex);
                return ClearString(Htmlstring);
            }

        }
        #endregion

        #region 汉字与十六进制互转

        /// <summary>
        /// 汉字转换为十六进制编码
        /// </summary>
        /// <param name="s">汉字字符串</param>
        /// <returns>十六进制编码</returns>
        public static string GetHexFromChs(string s)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格
                //throw new ArgumentException("s is not valid chinese string!");
            }

            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");

            byte[] bytes = chs.GetBytes(s);

            string str = "";

            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
            }

            return str;
        }

        /// <summary>
        /// 十六进制编码转换为汉字
        /// </summary>
        /// <param name="hex">十六进制编码</param>
        /// <returns>汉字字符串</returns>
        public static string GetChsFromHex(string hex)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
                //throw new ArgumentException("hex is not a valid number!", "hex");
            }
            // 需要将 hex 转换成 byte 数组。
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                        System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message.
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }

            // 获得 GB2312，Chinese Simplified。
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");


            return chs.GetString(bytes);
        }
        #endregion

        # region 问题类型判断

        #region 问题类型
        /* QuestionType
    QUT2008070100001	QuestionType		单选	        1
    QUT2008070100002	QuestionType		单选(带附件)	2
    QUT2008070100003	QuestionType		多选兼排序	    3
    QUT2008070100004	QuestionType		打分	        4
    QUT2008070100005	QuestionType		填空	        5
    QUT2008070100006	QuestionType		问答	        6   
    QUT2008070100007	QuestionType		排序	        7 
    */
        public static string QUOTE_TYPE_RADIOBOX = "QUT2008070100001";
        public static string QUOTE_TYPE_RADIOBOX_ATTACHMENT = "QUT2008070100002";
        public static string QUOTE_TYPE_CHECKBOX = "QUT2008070100003";
        public static string QUOTE_TYPE_POINT = "QUT2008070100004";
        public static string QUOTE_TYPE_TEXT = "QUT2008070100005";
        public static string QUOTE_TYPE_MEMO = "QUT2008070100006";
        public static string QUOTE_TYPE_ORDER = "QUT2008070100007";
        #endregion

        public static bool IsRadioBox(string aQTNo)
        {
            return (aQTNo == QUOTE_TYPE_RADIOBOX);
        }

        public static bool IsRadioBoxWithAttc(string aQTNo)
        {
            return (aQTNo == QUOTE_TYPE_RADIOBOX_ATTACHMENT);
        }

        public static bool IsCheckBox(string aQTNo)
        {
            return (aQTNo == QUOTE_TYPE_CHECKBOX);
        }

        public static bool IsPoint(string aQTNo)
        {
            return (aQTNo == QUOTE_TYPE_POINT);
        }

        public static bool IsText(string aQTNo)
        {
            return (aQTNo == QUOTE_TYPE_TEXT);
        }

        public static bool IsMemo(string aQTNo)
        {
            return (aQTNo == QUOTE_TYPE_MEMO);
        }
        public static bool IsOrder(string aQTNo)
        {
            return (aQTNo == QUOTE_TYPE_ORDER);
        }
        #endregion

        #region 问卷方法

        public static int MBoolToInt(bool value)
        {
            if (value)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public static bool MIntToBool(int value)
        {
            if (value == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool MStrToBool(string value)
        {
            if (value == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static int MStrToInt(string value)
        {
            if (value == null || value == "")
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(value);
            }
        }

        #region
        //保存校验函数
        public enum TCheckType { ctNull = 1, ctZero = 2, ctNumber = 3 };

        public static bool CheckValid(IList<string> arrRow, IList<string> arrFieldIndex, IList<string> arrCaption, IList<TCheckType> arrCheckType, bool aShowHint)
        {
            for (int i = 0; i <= arrFieldIndex.Count - 1; i++)
            {
                foreach (TCheckType Type in arrCheckType)
                {
                    if (CheckValid(arrRow[Convert.ToInt16(arrFieldIndex[i])].ToString(), arrCaption[i].ToString(), Type, aShowHint))
                        return false;
                }
            }

            return true;
        }

        public static bool CheckValid(string aValue, string aCaption, TCheckType Type, bool aShowHint)
        {
            if (Type == TCheckType.ctNull)
            {
                return CheckNull(aValue, aCaption, aShowHint);
            }
            else if (Type == TCheckType.ctZero)
            {
                return CheckZero(aValue, aCaption, aShowHint);
            }
            else if (Type == TCheckType.ctNumber)
            {
                return CheckInvalidNumber(aValue, aCaption, aShowHint);
            }
            else
            {
                return false;
            }
        }

        public static bool CheckNull(string aValue, string aCaption, bool aShowHint)
        {
            if (String.IsNullOrEmpty(aValue))
            {
                if (aShowHint)
                {
                    return false;
                    //Utility.Web.Alert(null,aCaption + "不允许为空！");
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool CheckZero(string aValue, string aCaption, bool aShowHint)
        {
            if (CheckInvalidNumber(aValue, aCaption, aShowHint))
            {
                return true;
            }

            if (Convert.ToInt16(aValue) == 0)
            {
                if (aShowHint)
                {
                    return false;
                    //csGlobal.MsgBox(aCaption + "不允许为零！");
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool CheckInvalidNumber(string aValue, string aCaption, bool aShowHint)
        {
            bool IsNumeric = System.Text.RegularExpressions.Regex.IsMatch(aValue, @"^[-]?\d+[.]?\d*$");
            if (IsNumeric)
            {
                return false;
            }
            else
            {
                if (aShowHint)
                {
                    return false;
                    //csGlobal.MsgBox(aCaption + "不是有效数字！");
                }
                return true;
            }
        }
        #endregion




        #endregion

        /// <summary>
        /// 写Cookies
        /// </summary>
        /// <param name="response"></param>
        /// <param name="request"></param>
        /// <param name="server"></param>
        /// <param name="IndexValue"></param>
        /// <param name="TextValue"></param>
        /// <param name="ExpriesHour">设置的过期时间</param>
        public static void WriteCookies(HttpResponse response, HttpRequest request, HttpServerUtility server, string IndexValue, string TextValue)
        {
            response.Cookies[IndexValue].Value = TextValue;
            response.Cookies[IndexValue].Expires = System.DateTime.Now.AddDays(15);
        }

        /// <summary>
        /// 读Cookies
        /// </summary>
        /// <param name="response"></param>
        /// <param name="request"></param>
        /// <param name="server"></param>
        /// <param name="IndexValue"></param>
        /// <returns></returns>
        public static string ReadCookies(HttpResponse response, HttpRequest request, HttpServerUtility server, string IndexValue)
        {
            if (request.Cookies[IndexValue] != null)
            {
                return request.Cookies[IndexValue].Value.ToString();
            }
            else
            {
                return "";
            }
        }

        public static void ClearCookies(HttpResponse response, HttpRequest request)
        {
            response.Cookies["AnJiCRM_UserName"].Expires = DateTime.Now.AddDays(-1);
            response.Cookies["AnJiCRM_Password"].Expires = DateTime.Now.AddDays(-1);
            response.Cookies.Clear();

            response.Cookies["AnJiCRM_UserName"].Value = "";
            response.Cookies["AnJiCRM_Password"].Value = "";
        }

        /// <summary>
        /// 下载文件方法
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="newFileName">新文件名</param>
        public void DownloadFile(string filePath, string newFileName)
        {
            System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
            try
            {
                long fileSize = fileStream.Length;
                HttpContext.Current.Response.ContentType = "application/octet-stream";


                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8).Replace("+", "") + "\"");
                HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
                byte[] fileBuffer = new byte[fileSize];
                fileStream.Read(fileBuffer, 0, (int)fileSize);
                if (fileBuffer.Length > 0)
                {
                    HttpContext.Current.Response.BinaryWrite(fileBuffer);
                }
                HttpContext.Current.Response.End();
            }
            finally
            {
                fileStream.Close();
            }
        }
    }
}